package com.qunar.wan.task;

import com.google.common.collect.Lists;
import com.qunar.wan.common_api.model.Activity;
import com.qunar.wan.common_api.model.User;
import com.qunar.wan.common_api.model.enums.EmailType;
import com.qunar.wan.common_api.service.ActivityService;
import com.qunar.wan.common_api.service.UserActivityService;
import com.qunar.wan.email.EmailSender;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * User: devry Date: 13-12-12 Time: 下午1:14
 */
@Component("evaluateNoticeTask")
public class EvaluateNoticeTask {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private UserActivityService userActivityService;
    @Resource
    private ActivityService activityService;

    public void run() {
        // 根据当前时间获得昨天举办完的活动
        List<Activity> activityList = activityService.selectByEndDay(new DateTime().plusDays(-1).toDate());
        // 根据活动id查询所有的参加者
        for (Activity activity : activityList) {
            // 查出活动的所有参与者
            List<User> userList = userActivityService.selectUsersByActId(activity.getId());
            List<String> userEmails = Lists.transform(userList, UserFunction.userToEmailFunction);
            // 给每个参与者发送邮件
            for (String userEmail : userEmails) {
                try {
                    long start = System.currentTimeMillis();
                    EmailSender.send(EmailType.ACTIVITY_END, activity, userEmail);
                    logger.info("EvaluateNoticeTask 于{} send email,actid is {},receiver is {},耗时{}", new Date(),
                            activity.getId(), userEmail, System.currentTimeMillis() - start);
                } catch (Exception e) {
                    logger.info("EvaluateNoticeTask 于{} send email,actid is {},receiver is {},occured an exception {}",
                            new Date(), activity.getId(), userEmail, e);
                    continue;
                }
            }
        }
    }

}
